﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Domain;
using Cms.Web.Framework.Controls;
using iLib.Web.UI;
using iLib.Web.UI.WebControls;
using Page = Cms.Domain.Page;

namespace Cms.Web.UI.Admin
{
    public partial class EditUserGroup : AdminPage, IEditUserGroupView
    {
        private EditUserGroupPresenter _presenter;

        #region IEditUserGroupView Members

        public int GroupID
        {
            get
            {
                if (hidUserGroupID.Value == "")
                    hidUserGroupID.Value = QueryString.GetInt32ID("id").ToString();
                return int.Parse(hidUserGroupID.Value);
            }
        }
        
        public void SetGroupID(int id)
        {
            hidUserGroupID.Value = id.ToString();
        }
        
        public string CurrentTab
        {
            get { return tabStrip.CurrentValue; }
        }

        public string Name
        {
            get { return txtName.Text; }
            set { txtName.Text = value; }
        }
        
        public void SetLoginFolders(string domain, IList<Folder> folders)
        {
            SetFolders(ref ddlLoginFolders, domain, folders);
        }
        
        public void SetStartFolders(string domain, IList<Folder> folders)
        {
            SetFolders(ref ddlStartFolders, domain, folders);
        }
        
        public int SelectedLoginFolderID
        {
            get { return int.Parse(ddlLoginFolders.SelectedValue); }
            set { ddlLoginFolders.SelectedValue = value.ToString(); }
        }

        public int SelectedStartFolderID
        {
            get { return int.Parse(ddlStartFolders.SelectedValue); }
            set { ddlStartFolders.SelectedValue = value.ToString(); }
        }
        
        public void SetLoginPages(IList<Page> pages)
        {
            SetPages(ref ddlLoginPages, ref lblNoLoginPages, pages);
        }

        public void SetStartPages(IList<Page> pages)
        {
            SetPages(ref ddlStartPages, ref lblNoStartPages, pages);
        }
        
        public int SelectedLoginPageID
        {
            get
            {
                if (lblNoLoginPages.Visible)
                    return -1;
                return int.Parse(ddlLoginPages.SelectedValue);
            }
            set { ddlLoginPages.SelectedValue = value.ToString(); }
        }
        
        public int SelectedStartPageID
        {
            get
            {
                if (lblNoStartPages.Visible)
                    return -1;
                return int.Parse(ddlStartPages.SelectedValue);
            }
            set { ddlStartPages.SelectedValue = value.ToString(); }
        }
        
        public string ContextTranslationFile
        {
            get { return "Admin/Translations/EditUserGroup.xml"; }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _presenter = new EditUserGroupPresenter(this);
            if (!Page.IsPostBack)
            {
                if (GroupID > 0)
                    tabStrip.SelectedValue = Request.QueryString["tab"];
                _presenter.Initialize();
                HeadingIcon = litIcon.Text;
                txtName.Focus();
            }
            HeadingText = GroupID > 0
                              ? GetText(this, "EditGroupHeading") + " &mdash; " + Name
                              : GetText(this, "NewGroupHeading");
        }

        private string GetSaveInfoMessageKey()
        {
            return GroupID > 0 ? "OptionalSaveInfoMessage" : "ForceSaveInfoMessage";
        }

        private string GetClientClickScript(AdminTabItem ti)
        {
            return "cms.Edit.ShowTabOverlays(); " +
                   "if (isDirty()) {" +
                   "return cms.Dialogs.Confirm(" +
                   "function (status) { " +
                   "document.getElementById('ctl00_tabs_hidSave').value = status;" +
                   "var groupID = document.getElementById('ctl00_tabs_hidUserGroupID').value;" +
                   "if ((groupID == '' || groupID == '-1') && status != 'ok') " +
                   "cms.Edit.HideTabOverlays(); " +
                   "else " +
                   "__doPostBack('" + ti.UniqueID + "$" + ti.ID + "','');" +
                   "}, " +
                   "'" + GetText(this, "SaveInfoHeader") + "', " +
                   "'" + GetText(this, GetSaveInfoMessageKey()) + "', " +
                   "'" + GetText(this, "SaveInfoOK") + "', " +
                   "'" + GetText(this, "SaveInfoCancel") + "', " +
                   "true, " +
                   "null" +
                   ");" +
                   "}";
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            tiProperties.OnClientClick = GetClientClickScript(tiProperties);
            tiFields.OnClientClick = GetClientClickScript(tiFields);
            hlNewField.NavigateUrl = "Admin/EditUserGroupField.aspx?usergroupid=" + GroupID;
            switch (iLib.Web.UI.ControlFinder.GetPostBackControlID())
            {
                case "ctl00$body$ddlLoginFolders":
                case "ctl00$body$ddlStartFolders":
                    return;
            }

            // Re-fetch the properties tab to keep them updated if the user chose not to save changes
            _presenter.RefreshProperties();
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);
            ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(),
                                                            "updatePanels",
                                                            "updatePanels('" + tabStrip.SelectedValue + "');", true);
            hlNewField.Visible = tabStrip.SelectedValue == "fields";
            lbSave.Visible = tabStrip.SelectedValue == "properties";
            hlCancel.Visible = tabStrip.SelectedValue == "properties";
            upnlButtons.Update();
        }

        protected void tabStrip_Click(string value)
        {
            if (CurrentTab == "properties" && hidSave.Value == "ok")
                _presenter.Save();
            if (_presenter.IsValid)
            {
                ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(), "init", "init();", true);
            }
            upnlFields.Update();
            upnlProperties.Update();
            upnlTabs.Update();
        }

        protected void lbSave_Click(object sender, EventArgs e)
        {
            _presenter.Save();
            if (_presenter.IsValid)
                Response.Redirect("UserGroups.aspx");
        }
        
        protected void ddlLoginFolders_Changed(object sender, EventArgs e)
        {
            _presenter.UpdateLoginPages();
            upnlProperties.Update();
        }
        
        protected void ddlStartFolders_Changed(object sender, EventArgs e)
        {
            _presenter.UpdateStartPages();
            upnlProperties.Update();
        }

        private void SetFolders(ref iDropDownList ddl, string domain, IList<Folder> folders)
        {
            ddl.Items.Clear();
            ddl.Items.Add(new ListItem(domain, "-1"));
            SetFolderTree(ref ddl, 1, folders);
        }

        public void SetPages(ref DropDownList ddl, ref Label lblNoPages, IList<Page> pages)
        {
            ddl.Items.Clear();
            ddl.Items.Add(new ListItem(GetText(this, "NoPageSelected"), "-1"));
            foreach (Page p in pages)
            {
                ddl.Items.Add(new ListItem(p.Name, p.ID.ToString()));
            }
            ddl.Visible = pages.Count > 0;
            lblNoPages.Visible = pages.Count == 0;
        }

        private void SetFolderTree(ref iDropDownList ddl, int level, IList<Folder> folders)
        {
            foreach (Folder f in folders)
            {
                string name = f.Name;
                for (int i = 0; i < level; i++)
                    name = "&nbsp;&nbsp;&nbsp;&nbsp;" + name;
                ddl.Items.Add(new ListItem(name, f.ID.ToString()));
                SetFolderTree(ref ddl, level + 1, f.SubFolders);
            }
        }
    }
}